<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户账号" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入用户账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="认证状态" prop="status">
        <!-- 认证状态（0-未认证，1-已认证，2-审核中，3-审核失败） -->
        <el-select v-model="queryParams.status" @change="handleQuery" placeholder="请选择认证状态" clearable style="width: 240px">
          <el-option label="未认证" value="0" />
          <el-option label="已认证" value="1" />
          <el-option label="审核中" value="2" />
          <el-option label="审核失败" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="主体名称" prop="entity">
        <el-input
          v-model="queryParams.entity"
          placeholder="主体名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['user:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['user:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账号" align="center" prop="phone" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="认证状态" align="center" prop="authStatus" >
        <template slot-scope="scope">
          <!-- 认证状态（0-未认证，1-已认证，2-审核中，3-审核失败） -->
          <el-tag v-if="scope.row.authStatus === '0'" type="info" size="mini" >未认证</el-tag>
          <el-tag v-if="scope.row.authStatus === '1'" type="success" size="mini" >已认证</el-tag>
          <el-tag v-if="scope.row.authStatus === '2'" type="warning" size="mini" >审核中</el-tag>
          <el-tag v-if="scope.row.authStatus === '3'" type="danger" size="mini" >审核失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="主体名称" align="center" prop="businessEntity" />
      <el-table-column label="注册时间" align="center" prop="regTime" />
      <el-table-column label="是否启用" align="center" prop="status" >
        <template slot-scope="scope">
          <!-- 用户状态（1-启用，2-禁用） -->
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="2" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <router-link :to="'/information/details/index/user/' + scope.row.userId + '/-'" v-hasPermi="['user:info:query']">
            <el-button size="mini" type="text" icon="el-icon-info" >用户详情</el-button>
          </router-link>
          <el-button size="mini" type="text" icon="el-icon-key"
            @click="handleGenerate(scope.row)" v-hasPermi="['user:info:tempPwd']" style="margin-left: 10px;">临时密码</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)" v-hasPermi="['user:info:remove']" style="margin-left: 10px;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <div>临时密码为：<b><el-link @click="copyText" type="primary">{{tempInfo.tempPwd || "-"}}</el-link></b>，有效期：{{tempInfo.expiration || "-"}}</div>
      <span slot="footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {listInfo, delInfo, changeUserStatus, generateTempPwd} from "@/api/business/user"

export default {
  name: "Users",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产人信息表格数据
      infoList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        account: null,
        status: null,
        entity: null,
      },
      dialogVisible: false,
      tempInfo: {},
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询生产人信息列表 */
    getList() {
      this.loading = true
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$modal.confirm('是否确认删除所选数据？').then(function() {
        return delInfo(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功！")
      }).catch(() => {})
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用"
      this.$modal.confirm('确定要'+text+'用户'+row.phone+'吗？').then(function() {
        return changeUserStatus(row.userId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功！")
      }).catch(function() {
        row.status = row.status === "1" ? "2" : "1"
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('user/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },

    handleGenerate(row){
      let that = this;
      that.$confirm('确定生成临时密码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.loading = true;
        generateTempPwd(row.userId).then(response => {
          that.loading = false;
          that.tempInfo = response.data;
          that.tempInfo.user = row.phone;
          that.dialogVisible = true;
        })
      }).catch(() => {
      });
    },
    async copyText() {
      try {
        let text = "账号"+this.tempInfo.user+"的临时密码为：" + this.tempInfo.tempPwd + "，有效期："+this.tempInfo.expiration
        // await navigator.clipboard.writeText(text);
        const textarea = document.createElement("textarea");
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand("copy");
        document.body.removeChild(textarea);
        this.$modal.msgSuccess("文本已复制到剪贴板！")
      } catch (err) {
        this.$modal.msgError("无法复制文本，请手动选择并复制！")
      }
    },
  }
}
</script>
